<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { TopLeft } from '@element-plus/icons-vue'
import { useUtilsStore } from '@/stores/index'
import { WarnTriangleFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/index'

const Mail = ref({ mail: '', username: '' })
const formRef = ref()
const isDark = ref(false)
const isInputDisabled = ref(false)
const countdown = ref(60) // 倒计时初始值
const timer = ref(null) // 定时器
const utils = useUtilsStore()
const UserStore = useUserStore()
// 组件加载时检查 localStorage

const checkLocalStorage = () => {
  const savedCountdown = localStorage.getItem('countdown')
  const savedIsInputDisabled = localStorage.getItem('isInputDisabled')
  if (savedCountdown) {
    countdown.value = parseInt(savedCountdown, 10) // 恢复倒计时
    isInputDisabled.value = savedIsInputDisabled === 'true' // 恢复输入框状态

    if (isInputDisabled.value) {
      startTimer() // 如果输入框禁用，则启动倒计时
    }
  }
}
onMounted(() => {
  checkLocalStorage()
})

// 启动定时器
const startTimer = () => {
  timer.value = setInterval(() => {
    countdown.value -= 1 // 递减倒计时
    localStorage.setItem('countdown', countdown.value) // 更新 localStorage

    if (countdown.value <= 0) {
      clearInterval(timer.value) // 清除定时器
      isInputDisabled.value = false // 恢复输入框
      localStorage.removeItem('countdown') // 清除 localStorage
      localStorage.removeItem('isInputDisabled') // 清除状态
    }
  }, 1000) // 每秒递减
}
const SubEmail = async () => {
  await ElMessageBox.confirm(`请再次确认您的手机号：${Mail.value.mail}`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    icon: WarnTriangleFilled,
    draggable: true
  })
  // 先通过 formRef 进行校验
  await formRef.value.validate()

  // 校验通过后执行你的提交逻辑
  // 重置倒计时
  if (timer.value) {
    clearInterval(timer.value) // 清除之前的定时器
  }

  isInputDisabled.value = true // 禁用输入框
  countdown.value = 59 // 重置倒计时为60秒
  Mail.value.username = UserStore.user.name // 保存用户名到数据中
  utils.submitEmail(Mail.value) // 调用接口提交数据
  Mail.value.mail = ''
  localStorage.setItem('isInputDisabled', isInputDisabled.value) // 存储输入框状态到 localStorage
  localStorage.setItem('countdown', countdown.value) // 存储剩余时间到 localStorage

  // 开始倒计时
  startTimer()
}
const rules = {
  mail: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { min: 11, max: 11, message: '手机号长度为11位', trigger: 'blur' }
  ]
}
// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})
</script>

<template>
  <div>
    <h3>上传游戏</h3>
    <div class="title">
      上传游戏请上传
      <div class="red">联系方式</div>
      ，管理员会在24小时内联系您，请耐心等待...
    </div>
    <div class="test">
      <el-form size="large" autocomplete="off" :model="Mail" ref="formRef" :rules="rules">
        <el-form-item prop="mail" class="input" label="联系方式">
          <el-input
            v-model="Mail.mail"
            class="w-50 m-2"
            placeholder="输入你的联系方式（手机号）"
            clearable
            :prefix-icon="TopLeft"
            :disabled="isInputDisabled"
          ></el-input>

          <el-tooltip
            class="box-item"
            effect="dark"
            content="提示：此消息会发送给管理员，请谨慎填写"
            placement="top-start"
          >
            <el-button
              v-if="Mail.mail"
              :disabled="isInputDisabled"
              color="#027efb"
              :dark="isDark"
              plain
              @click="SubEmail()"
              >发送信息</el-button
            >
          </el-tooltip>
          <div v-if="isInputDisabled" class="countdown">{{ countdown }} 秒后可重新发送</div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style scoped lang="scss">
h3 {
  color: #027efb;
}
.title {
  display: flex;
  .red {
    color: #027efb;
  }
}
.test {
  .input {
    display: flex;
    margin-top: 20px;
    .w-50.m-2 {
      width: 50%;
      margin-right: 20px;
    }
  }
}
</style>
